#!/usr/bin/perl -w

BEGIN   
{
	sub getPoints{return '../../' if (!$_[1]);return '../' if (!$_[0]);return '/';}
	(my $file = __FILE__) =~ s/\/?(modules\/)?(http_traffic_limit\/)?(\w+\.pl)$/&getPoints($1,$2)/e;
	$file = './' if $file eq '/';
	unshift(@INC, $file."bin");
	unshift(@INC, $file.'modules/http_bandwidth');
	unshift(@INC, $file.'modules/http_logging');
	unshift(@INC, $file.'modules/http_traffic_limit');
}

use strict;
use TWM;
use TrafficLimit;
use Logging;
use Bandwidth;

my $objTrafficLimit = TrafficLimit->new();
my $objBandWidth = Bandwidth->new();
my $logging = new Logging;
my $bandwidth = new Bandwidth;
my $http_logging_code = $logging->{this_module_code};
populateCfromConfig($http_logging_code);
my $http_bandwidth_code = $bandwidth->{this_module_code};
populateCfromConfig($http_bandwidth_code);

my $squid_settings = $logging->getSquidsSettings();

my $xml = &readModuleConfigFile($cm{pool});
my @items = $objBandWidth->convertPool2Array($xml);
my @dest = $objTrafficLimit->get_dest_list();
my $acl = "acl	{\n";

my $conf_str = <<__EOF;
logdir $cm{log_dir}
dbhome $cm{db_dir}

# time ranges
time leisure-time	{
	weekly * 00:00-08:00 22:00-24:00
	weekly sat sun 00:00-24:00
	date*.01.01
}
__EOF

my $hostname = `$ck{hostname}`;
chomp $hostname;

foreach my $d (@dest)
{
	next unless $d;
	$conf_str .= "dest $d {\n";
	$conf_str .= add_dest_item($d, $_) foreach ('domain', 'expression', 'url');
	$conf_str .= "}	\n";
}

if ($cm{redirect_ads})
{
	$conf_str =~ s/(dest ads {\n.+\n.+\n.+)(\n})/$1\n\tredirect\thttp:\/\/$hostname.$ck{_domain_name}:$ck{httpd_port}\/modules\/$mc\/pixel.gif$2/g;
}

foreach (@items)
{
	#next if !(exists($_->{disable}->{destination}) && exists($_->{content}->{ip}));
	(my $name = $_->{label}.'_'.$_->{name}) =~ s/[\W\s]//g;
	my $ips = ref $_->{content}->{ip} eq 'ARRAY'?join(" ", @{$_->{content}->{ip}}):$_->{content}->{ip};

	$conf_str .= <<__EOF;
src $name	{
	ip $ips
}
__EOF

	my $acl_s = '';
	if (exists $_->{disable}->{destination})
	{
		$acl_s = ref $_->{disable}->{destination} eq 'ARRAY'?"!".join(" !", @{$_->{disable}->{destination}}):"!".$_->{disable}->{destination};
	}

	$acl .= <<__EOF;
    $name	{
	pass $acl_s all
	redirect http://$hostname.$ck{_domain_name}:$ck{httpd_port}/cgi-bin/modules/$mc/$cm{redirect_url}
    }
__EOF

}

if ($cm{pass_by_default})
{
	$acl .= "	default {
	pass all
	}
}\n";
}
else
{
	$acl .= "   default {
	pass none
	redirect http://$hostname.$ck{_domain_name}:$ck{httpd_port}/cgi-bin/modules/$mc/$cm{redirect_url}
	log $cm{log_dir}/default.log
	}
}\n";
}

backupUserConfigFiles($cm{guard_config_file});
overwriteFile($cm{guard_config_file}, $conf_str.$acl);

foreach my $v (values %$squid_settings)
{
	run_twm_script("$C->{$http_bandwidth_code}->{reconfigure_squid} $v->{config}", $http_bandwidth_code);
}


sub add_dest_item
{
	if (-e "$cm{db_dir}/$_[0]/$_[1]s")
	{
		return "	$_[1]list		$_[0]/$_[1]s\n";
	}
	return '';
}

__END__
